package com.imut.lagain.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.imut.lagain.entity.DataOperationLog;
import com.imut.lagain.service.IDataOperationLogService;
import com.imut.lagain.util.JwtUtil;
import com.imut.lagain.util.ValidationUtil;
import jakarta.validation.constraints.*;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;



import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据操作日志控制器
 */
@RestController
@RequestMapping("/api/data-operation-log")
@RequiredArgsConstructor
@Validated
public class DataOperationLogController {
    private static final Logger log = LoggerFactory.getLogger(DataOperationLogController.class);
    
    private final IDataOperationLogService dataOperationLogService;
    private final JwtUtil jwtUtil;
    
    /**
     * 分页查询操作日志
     * @param authorization JWT令牌
     * @param page 页码
     * @param size 每页大小
     * @param userId 用户ID
     * @param operationType 操作类型
     * @param tableName 表名
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 操作日志列表
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getOperationLogs(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @RequestParam(defaultValue = "1") @Min(1) @Max(1000) int page,
            @RequestParam(defaultValue = "20") @Min(1) @Max(100) int size,
            @RequestParam(required = false) @Min(1) Long userId,
            @RequestParam(required = false) @Pattern(regexp = "^(CREATE|UPDATE|DELETE|SELECT)$") String operationType,
            @RequestParam(required = false) @Size(max = 100) String tableName,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Page<DataOperationLog> logPage = dataOperationLogService.getLogsByConditions(
                    userId, operationType, tableName, startTime, endTime, page, size);
            
            response.put("success", true);
            response.put("data", logPage);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to get operation logs", e);
            response.put("success", false);
            response.put("message", "获取操作日志失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 根据用户ID查询操作日志
     * @param authorization JWT令牌
     * @param userId 用户ID
     * @param page 页码
     * @param size 每页大小
     * @return 操作日志列表
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> getLogsByUserId(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @PathVariable @Min(1) Long userId,
            @RequestParam(defaultValue = "1") @Min(1) @Max(1000) int page,
            @RequestParam(defaultValue = "20") @Min(1) @Max(100) int size) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Page<DataOperationLog> pageParam = new Page<>(page, size);
            IPage<DataOperationLog> logPage = dataOperationLogService.getLogsByUserId(userId, pageParam);
            
            response.put("success", true);
            response.put("data", logPage);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to get logs by user id", e);
            response.put("success", false);
            response.put("message", "获取用户操作日志失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 根据操作类型查询日志
     * @param authorization JWT令牌
     * @param operationType 操作类型
     * @param page 页码
     * @param size 每页大小
     * @return 操作日志列表
     */
    @GetMapping("/type/{operationType}")
    public ResponseEntity<Map<String, Object>> getLogsByOperationType(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @PathVariable String operationType,
            @RequestParam(defaultValue = "1") @Min(1) @Max(1000) int page,
            @RequestParam(defaultValue = "20") @Min(1) @Max(100) int size) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            if (!operationType.matches("^(CREATE|UPDATE|DELETE|SELECT)$")) {
                response.put("success", false);
                response.put("message", "无效的操作类型");
                return ResponseEntity.badRequest().body(response);
            }
            
            Page<DataOperationLog> pageParam = new Page<>(page, size);
            IPage<DataOperationLog> logPage = dataOperationLogService.getLogsByOperationType(operationType, pageParam);
            
            response.put("success", true);
            response.put("data", logPage);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to get logs by operation type", e);
            response.put("success", false);
            response.put("message", "获取操作类型日志失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 获取操作统计信息
     * @param authorization JWT令牌
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 统计信息
     */
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getOperationStats(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Map<String, Object> stats = new HashMap<>();
            stats.put("totalOperations", dataOperationLogService.countOperations(startTime, endTime));
            stats.put("operationTypeStats", dataOperationLogService.getOperationTypeStats(startTime, endTime));
            stats.put("tableOperationStats", dataOperationLogService.getTableOperationStats(startTime, endTime));
            stats.put("userOperationStats", dataOperationLogService.getUserOperationStats(startTime, endTime));
            
            response.put("success", true);
            response.put("data", stats);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to get operation stats", e);
            response.put("success", false);
            response.put("message", "获取操作统计失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 获取最近操作日志
     * @param authorization JWT令牌
     * @param limit 限制数量
     * @return 最近操作日志
     */
    @GetMapping("/recent")
    public ResponseEntity<Map<String, Object>> getRecentLogs(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @RequestParam(defaultValue = "10") @Min(1) @Max(100) int limit) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            List<DataOperationLog> recentLogs = dataOperationLogService.getRecentLogs(limit);
            
            response.put("success", true);
            response.put("data", recentLogs);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to get recent logs", e);
            response.put("success", false);
            response.put("message", "获取最近日志失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 清理过期日志
     * @param authorization JWT令牌
     * @param days 保留天数
     * @return 清理结果
     */
    @DeleteMapping("/cleanup")
    public ResponseEntity<Map<String, Object>> cleanupExpiredLogs(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @RequestParam(defaultValue = "30") @Min(1) @Max(365) int days) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            int deletedCount = dataOperationLogService.cleanupExpiredLogs(days);
            
            response.put("success", true);
            response.put("message", "清理完成");
            response.put("deletedCount", deletedCount);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to cleanup expired logs", e);
            response.put("success", false);
            response.put("message", "清理过期日志失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }
}
